package pri.hillchen.springbootstd.bms.common.base;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * @author:hillchen
 * @DESCRIPTION: 对controller层中所有的拥有RequestMapping注解的方法进行拦截添加自己代码处理逻辑
 * 如：请求日志记录
 * @Date: Created in 15:32 2017/10/20 0020.
 */
@Component
public class ControllerBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class clazz = bean.getClass();
        /**
         * 判断该bean是否为一个controller bean
         */
        //如果注册的bean不属于Controller，直接跳出
        if (!clazz.isAnnotationPresent(Controller.class)) {
            return bean;
        }
        try{
            ControllerProxy daoProxy = new ControllerProxy(bean);

            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(clazz);
            enhancer.setCallback(daoProxy);
            bean = enhancer.create();
        }catch (Exception e){
            //输出异常日志
            return bean;
        }

        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
